#!/usr/bin/python
# -*- coding: utf-8 -*-

#Author: Yuanhao Li <jay_21cn@hotmail.com>
#File: ingcapp.py
#Usage: Client of ING from project Babel
#Copyright (C) 2007 Yuanhao Li<jay_21cn@hotmail.com>

#This program is free software; you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation; either version 2 of the License, or
#(at your option) any later version.

#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.

#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software Foundation,
#Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

#本程序是遵从 GPL 2.0 许可发布的. 你可以自由修改和再发布本程序, 
#但请遵守 GPL 2.0 条款, 尊重知识产权.

import sys, os, thread

from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import QVariant, QThread, QStringList

from ingcapp_ui import Ui_MainWindow
from tabmanager import TabManager
from logindialog import loginDialog
import ingcinfobase as Info

cwd = os.path.split(sys.argv[0])[0]
if not cwd:
	cwd = os.getcwd()

class IngcApp(QtGui.QMainWindow):
	def __init__(self, parent = None):
		QtGui.QWidget.__init__(self, parent)
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)

		self.setStyleSheet("*{font-size: 12px;}")

		self.ui.textBrowser.append(Info.IngcStartIntro)
		self.ui.textBrowser.setOpenExternalLinks(True)
		self.ui.textBrowser.setStyleSheet('QTextBrowser{background: #edf3fe; font-size: 14px;}')
		self.ui.textBrowser.setSearchPaths(QStringList(cwd))
		self.ui.textEdit.installEventFilter(self)
		self.ui.textEdit.setEnabled(False)
		self.ui.textEdit.setAcceptRichText(False)
		QtCore.QObject.connect(self.ui.textEdit, QtCore.SIGNAL('textChanged ()'), self.checkIngSize)

		self.setting = QtCore.QSettings('Yuanhao Li', 'INGC')
		self.setting.beginGroup('MainWindow')
		self.move(self.setting.value('pos', QVariant(QtCore.QPoint(200, 200))).toPoint())
		self.resize(self.setting.value('size', QVariant(QtCore.QSize(550, 590))).toSize())
		self.setting.endGroup()

		self.statusBarLabelStatus = QtGui.QLabel('', self)
		self.statusBarLabelStatus.setMargin(3)
		self.statusBarLabelStatus.setStyleSheet('QLabel{color: #333333;}')
		self.statusBarLabelWhen = QtGui.QLabel('', self)
		self.statusBarLabelWhen.setMargin(3)
		self.statusBarLabelWhen.setStyleSheet('QLabel{color: #333333;}')
		self.statusBarLabelPeriod = QtGui.QLabel('', self)
		self.statusBarLabelPeriod.setMargin(3)
		self.statusBarLabelPeriod.setStyleSheet('QLabel{color: #333333;}')
		self.ui.statusbar.insertPermanentWidget(0, self.statusBarLabelWhen)
		self.ui.statusbar.insertPermanentWidget(1, self.statusBarLabelPeriod)
		self.ui.statusbar.insertPermanentWidget(2, self.statusBarLabelStatus)
		#self.ui.statusbar.setSizeGripEnabled(False)
		backgroundColor = self.palette().color(QtGui.QPalette.Normal, QtGui.QPalette.Background)
		self.ui.statusbar.palette().setColor(QtGui.QPalette.Normal, QtGui.QPalette.Dark, backgroundColor)
		self.ui.statusbar.palette().setColor(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, backgroundColor)
		self.ui.statusbar.palette().setColor(QtGui.QPalette.Active, QtGui.QPalette.Dark, backgroundColor)
		self.ui.statusbar.palette().setColor(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, backgroundColor)
		self.ui.statusbar.palette().setColor(QtGui.QPalette.Normal, QtGui.QPalette.Light, backgroundColor)
		self.ui.statusbar.palette().setColor(QtGui.QPalette.Disabled, QtGui.QPalette.Light, backgroundColor)
		self.ui.statusbar.palette().setColor(QtGui.QPalette.Active, QtGui.QPalette.Light, backgroundColor)
		self.ui.statusbar.palette().setColor(QtGui.QPalette.Inactive, QtGui.QPalette.Light, backgroundColor)

		if QtGui.QSystemTrayIcon.isSystemTrayAvailable():
			self.trayIcon = QtGui.QSystemTrayIcon(QtGui.QIcon(cwd + "/pixmaps/ingc.png"), self)
			QtCore.QObject.connect(self.trayIcon, QtCore.SIGNAL("activated(QSystemTrayIcon::ActivationReason)"), self.onTrayIcon)
			self.trayMenu = QtGui.QMenu(self)
			self.trayMenu.addAction(self.ui.actionConnect)
			#self.trayMenu.addAction(self.ui.actionOption)
			self.trayMenu.addAction(self.ui.actionExit)
			self.trayIcon.setContextMenu(self.trayMenu)
			self.trayIcon.setVisible(True)

		self.closeBtn = QtGui.QToolButton(self)
		self.closeBtn.setIconSize(QtCore.QSize(16, 16))
		self.closeBtn.setIcon(QtGui.QIcon(cwd + "/pixmaps/cross.png"))
		self.closeBtn.setGeometry(self.width() - 14, 22, 12, 12)
		self.closeBtn.setShortcut("Ctrl+W")
		self.closeBtn.setAutoRaise(True)
		self.closeBtn.setToolTip(QtCore.QString(u'关闭当前标签页'))
		QtCore.QObject.connect(self.closeBtn, QtCore.SIGNAL("clicked()"), self.doCloseTab)
		self.tab = TabManager(self.ui.tabWidget)

		QtCore.QObject.connect(self.ui.actionReconnect, QtCore.SIGNAL('triggered()'), self.reconnect)
		QtCore.QObject.connect(self.ui.actionDisconnect, QtCore.SIGNAL('triggered()'), self.disconnect)
		QtCore.QObject.connect(self.ui.actionExit, QtCore.SIGNAL('triggered()'), self.closeApp)
		QtCore.QObject.connect(self.ui.actionConnect, QtCore.SIGNAL('triggered()'), self.openLoginDialog)

		self.ui.actionDisconnect.setEnabled(False)
		self.ui.actionReconnect.setEnabled(False)

		QtCore.QObject.connect(self.ui.tabWidget, QtCore.SIGNAL('currentChanged(int)'), self.onTabChanged)

		self.macInputMethodeFlag = 0

	def openLoginDialog(self):
		if not hasattr(self, 'dialog'):
			self.dialog = loginDialog(self.setting, self)
			self.dialog.show()
		else:
			if self.dialog.isHidden():
				self.dialog = loginDialog(self.setting, self)
				self.dialog.show()

	def checkIngSize(self):
		if len(self.ui.textEdit.toPlainText().simplified()) - 5 > 131:
			self.ui.textEdit.setStyleSheet('QTextEdit{border: 2px solid #ff9166}')
		else:
			self.ui.textEdit.setStyleSheet('')

	def closeApp(self):
		self.hide()
		self.trayIcon.setVisible(False)

		self.setting.beginGroup('MainWindow')
		self.setting.setValue('size', QVariant(self.size()))
		self.setting.setValue('pos', QVariant(self.pos()))
		self.setting.endGroup()

		if hasattr(self, 'dialog'):
			self.dialog.close()
		del self.trayIcon
		self.thread().setPriority(QThread.TimeCriticalPriority)
		for v in self.tab.getViews():
			if hasattr(v, 'threadGetNewItems'):
				v.threadGetNewItems.setSleepTime(1)
				v.threadGetNewItems.setRunning(False)
		finished = False
		while not finished:
			temp = True
			for v in self.tab.getViews():
				if hasattr(v, 'threadGetNewItems'):
					temp = temp and v.threadGetNewItems.stop
				if hasattr(v, 'threadLogin'):
					temp = temp and v.threadLogin.stop
				if hasattr(v, 'threadRequestHotTopics'):
					temp = temp and v.threadRequestHotTopics.stop
			QThread.sleep(1)
			finished = temp

		pixmapsDir = QtCore.QDir(cwd + '/cache')
		files = pixmapsDir.entryList(QtCore.QDir.Files)
		for i in files:
			pixmapsDir.remove(i)
		self.close()

	def moveEvent(self, evt):
		self.postion = evt.pos()

	def onTrayIcon(self, reason):
		if reason == QtGui.QSystemTrayIcon.Trigger:
			if self.isVisible() == True:
				self.postion = self.pos()
				self.hide()
			else:
				self.move(self.postion)
				self.show()

	def eventFilter(self, obj, evt):
		if obj == self.ui.textEdit:
			if evt.type() == QtCore.QEvent.KeyPress:
				if evt.key() == QtCore.Qt.Key_Enter or evt.key() == QtCore.Qt.Key_Return:
					self.doUserInput()
					return True
				else:
					return False
			elif evt.type() == QtCore.QEvent.InputMethod:
				#print self.ui.textEdit.inputContext().identifierName()
				#print self.ui.textEdit.inputContext().isComposing()
				#print self.ui.textEdit.inputContext().language()
				#commitString = evt.commitString()
				#preeditString = evt.preeditString()
				#print 'commitString: ' + commitString.toUtf8()
				#print 'preeditString: ' + preeditString.toUtf8()
				#print '--'
				##if sys.platform[:5] == 'linux':
				##	self.ui.textEdit.insertPlainText(commitString)
				#if sys.platform == 'darwin':
				#	if self.macInputMethodeFlag == 1:
						##self.ui.textEdit.insertPlainText(commitString)
				#		evt.setCommitString('')
				#	if commitString == '':
				#		self.macInputMethodeFlag = 0
				#	if preeditString == '' and commitString != '' and self.macInputMethodeFlag == 0:
				#		self.macInputMethodeFlag = 1
				#	if preeditString == '' and commitString == '':
				#		self.macInputMethodeFlag = 2
				#	return False
				#else:
				#	return False
				return False
			else:
				return False
		else:
			return QtGui.QMainWindow.eventFilter(self, obj, evt)

	def doUserInput(self):
		if self.tab.getCurrentViewIndex() != 0:
			if self.tab.getCurrentView().receiveUserCommand(self.ui.textEdit.toPlainText ()):
				self.ui.textEdit.clear()
				self.ui.textEdit.update()

	def doCloseTab(self):
		if self.tab.getCurrentViewIndex() != 0:
			self.tab.removeCurrentView()
		self.onTabChanged(self.tab.getCurrentViewIndex())

	def resizeEvent(self, evt):
		QtGui.QWidget.resizeEvent(self, evt)
		self.closeBtn.setGeometry(evt.size().width() - 14, 22, 12, 12)

	def onTabChanged(self, i):
		self.statusBarLabelStatus.setText('')
		self.statusBarLabelWhen.setText('')
		self.statusBarLabelPeriod.setText('')
		if i == 0:
			self.ui.actionConnect.setEnabled(True)
			self.ui.actionConnect.setShortcut(QtGui.QApplication.translate("MainWindow", "Ctrl+L", None, QtGui.QApplication.UnicodeUTF8))
			self.ui.actionReconnect.setEnabled(False)
			self.ui.actionReconnect.setShortcut(QtGui.QApplication.translate("MainWindow", "", None, QtGui.QApplication.UnicodeUTF8))
			self.ui.actionDisconnect.setEnabled(False)
			self.ui.actionDisconnect.setShortcut(QtGui.QApplication.translate("MainWindow", "", None, QtGui.QApplication.UnicodeUTF8))
			self.ui.textEdit.setEnabled(False)
		else:
			self.tab.setCurrentTabGaryStar()
			self.ui.actionConnect.setEnabled(True)
			self.ui.actionConnect.setShortcut(QtGui.QApplication.translate("MainWindow", "Ctrl+L", None, QtGui.QApplication.UnicodeUTF8))
			#if hasattr(self.tab.getCurrentViewPerIndex(i), 'period'):
			#	print self.tab.getCurrentViewPerIndex(i).period
			if self.tab.getCurrentViewPerIndex(i) is not None:
				if self.tab.getCurrentViewPerIndex(i).isLogined():
					self.ui.actionReconnect.setEnabled(False)
					self.ui.actionReconnect.setShortcut(QtGui.QApplication.translate("MainWindow", "", None, QtGui.QApplication.UnicodeUTF8))
					self.ui.actionDisconnect.setEnabled(True)
					self.ui.actionDisconnect.setShortcut(QtGui.QApplication.translate("MainWindow", "Ctrl+D", None, QtGui.QApplication.UnicodeUTF8))
					self.ui.textEdit.setEnabled(True)
					self.ui.textEdit.setFocus()
					self.tab.setStatusBarMode(self.tab.getCurrentViewPerIndex(i))
					self.tab.setStatusBarPeriod(self.tab.getCurrentViewPerIndex(i))
					if hasattr(self.tab.getCurrentViewPerIndex(i), 'updateTime'):
						self.tab.setStatusBarLastUpdate(self.tab.getCurrentViewPerIndex(i))
				else:
					self.ui.textEdit.setEnabled(False)
					if self.tab.getCurrentViewPerIndex(i).isReconnected():
						self.ui.actionDisconnect.setEnabled(False)
						self.ui.actionDisconnect.setShortcut(QtGui.QApplication.translate("MainWindow", "", None, QtGui.QApplication.UnicodeUTF8))
						self.ui.actionReconnect.setEnabled(True)
						self.ui.actionReconnect.setShortcut(QtGui.QApplication.translate("MainWindow", "Ctrl+R", None, QtGui.QApplication.UnicodeUTF8))
						self.tab.setStatusBarMode(self.tab.getCurrentViewPerIndex(i))
						self.tab.setStatusBarPeriod(self.tab.getCurrentViewPerIndex(i))
						self.tab.setStatusBarLastUpdate(self.tab.getCurrentViewPerIndex(i))
					else:
						self.ui.actionReconnect.setEnabled(False)
						self.ui.actionReconnect.setShortcut(QtGui.QApplication.translate("MainWindow", "", None, QtGui.QApplication.UnicodeUTF8))
						self.ui.actionDisconnect.setEnabled(False)
						self.ui.actionDisconnect.setShortcut(QtGui.QApplication.translate("MainWindow", "", None, QtGui.QApplication.UnicodeUTF8))

	def addView(self, url, usr, usr_pwd, proxy):
		self.tab.addView(url, usr, usr_pwd, proxy)

	def currentViewLogin(self):
		self.tab.currentViewConnect()
		QtCore.QObject.connect(self.tab.getCurrentView().threadLogin, QtCore.SIGNAL('doLogin'), self.onLogin)

	def onLogin(self):
		if self.tab.getCurrentView().isLogined() and self.tab.getCurrentViewIndex() != 0:
			self.ui.actionDisconnect.setEnabled(True)
			self.ui.actionDisconnect.setShortcut(QtGui.QApplication.translate("MainWindow", "Ctrl+D", None, QtGui.QApplication.UnicodeUTF8))
			self.ui.actionReconnect.setEnabled(False)
			self.ui.actionReconnect.setShortcut(QtGui.QApplication.translate("MainWindow", "", None, QtGui.QApplication.UnicodeUTF8))
			self.ui.textEdit.setEnabled(True)
			self.ui.textEdit.setFocus()

	def reconnect(self):
		self.tab.currentViewReconnect()
		self.ui.actionReconnect.setEnabled(False)
		self.ui.actionReconnect.setShortcut(QtGui.QApplication.translate("MainWindow", "", None, QtGui.QApplication.UnicodeUTF8))
		self.ui.actionDisconnect.setEnabled(True)
		self.ui.actionDisconnect.setShortcut(QtGui.QApplication.translate("MainWindow", "Ctrl+D", None, QtGui.QApplication.UnicodeUTF8))
		self.ui.textEdit.setEnabled(True)
		self.ui.textEdit.setFocus()

	def disconnect(self):
		self.tab.currentDisconnect()
		self.ui.actionReconnect.setEnabled(True)
		self.ui.actionReconnect.setShortcut(QtGui.QApplication.translate("MainWindow", "Ctrl+R", None, QtGui.QApplication.UnicodeUTF8))
		self.ui.actionDisconnect.setEnabled(False)
		self.ui.actionDisconnect.setShortcut(QtGui.QApplication.translate("MainWindow", "", None, QtGui.QApplication.UnicodeUTF8))
		self.ui.textEdit.setEnabled(False)

	def changeFont(self, font):
		styleCandidate = ['normal', 'italic', 'oblique']
		family = font.family()
		size = font.pixelSize()
		if size < 0:
			size = font.pointSize()
		style = styleCandidate[font.style()]
		weight = 'normal'
		if font.weight() != 50:
			weight = 'bold'
		stylesheet = 'QTextBrowser{font-family: "' + family + '"; font-size: ' + str(size) + 'px; font-style: ' + style + '; font-weight: ' + weight + ';}'
		for view in self.tab.getViews():
			view.setFont(font)
